<template>
  <el-dialog
    :title="title"
    :modal="false"
    :visible.sync="open"
    width="800px"
    :close-on-click-modal="false"
    custom-class="broadcast-dialog"
    :before-close="handleClose"
  >
    <el-input
      placeholder="请输入文件名称"
      v-model="searchKey"
      class="search-input"
      size="small"
      autocomplete
      @blur="filterTable"
    >
      <i slot="prefix" class="el-input__icon el-icon-search"></i>
    </el-input>
    <el-table
      ref="filterTable"
      :data="filterData()"
      height="400"
      style="width: 100%"
      :highlight-current-row="true"
      @current-change="currentRowChange"
      cell-class-name="table-cell-custom"
      header-cell-class-name="table-herder-custom"
      size="small"
      @selection-change="selectionChange"
    >
      <el-table-column width="55" type="selection" align="center"></el-table-column>
      <el-table-column prop="orifilename" show-overflow-tooltip label="文件名称"></el-table-column>
      <!-- <el-table-column prop="filesize" label="文件大小(KB)" width="180"></el-table-column> -->
      <!-- <el-table-column prop="remark" label="备注"></el-table-column> -->
      <el-table-column align="center" width="180">
        <template slot-scope="scope">
          <el-link icon="el-icon-headset" v-if="isAdmin == 0" @click="handleTrail(scope.row)">试听</el-link>
          <!-- <el-link icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-link> -->
        </template>
      </el-table-column>
    </el-table>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleUpload" size="small">上 传</el-button>
      <el-button @click="handleDelete" size="small">删 除</el-button>
      <el-button @click="handleCommit" v-if="isAdmin == 0 && !isDataManage" size="small">确 定</el-button>
    </div>
    <!-- 语音文件编辑 -->
    <el-dialog
      v-if="editVisible"
      :title="editTitle"
      :modal="false"
      custom-class="inner-dialog"
      :visible.sync="editVisible"
      width="100%"
    >
      <svg-icon class="back-to-list" icon-class="back" @click="editVisible = false"></svg-icon>
      <el-form
        ref="edit-form"
        :model="form"
        label-width="120px"
        :rules="rules"
        hide-required-asterisk
      >
        <el-form-item label="文件名称：" v-if="form.fileid">
          <el-input size="small" v-model="form.orifilename" disabled></el-input>
        </el-form-item>
        <el-form-item label="文件名称：" v-else prop="orifilename">
          <el-input size="small" v-model="form.orifilename" disabled></el-input>
          <el-upload
            class="upload-file"
            ref="upload-file"
            :accept="accept"
            :auto-upload="false"
            :show-file-list="false"
            :action="uploadUrl()"
            :headers="uploadHeaders"
            :on-change="uploadChange"
            :file-list="fileList"
          >
            <el-button size="small">选择文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="文件大小(KB)：" v-if="editTitle == '语音文件编辑'">
          <el-input size="small" v-model="form.filesize" disabled></el-input>
        </el-form-item>
        <el-form-item label="备注：" v-if="editTitle == '语音文件编辑'">
          <el-input type="textarea" :rows="10" v-model="form.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="form.fileid" size="small" @click="updateVoice">确 定</el-button>
        <el-button v-else :loading="uploading" size="small" @click="uploadVoice">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 试听窗口 -->
    <el-dialog
      title="语音文件试听"
      :modal="false"
      custom-class="inner-dialog"
      :visible.sync="trialVisible"
      width="100%"
      :show-close="false"
    >
      <div class="trial-box">
        <el-row>
          <svg-icon class="trial-loading" icon-class="loading" @click="editVisible = false"></svg-icon>
          <span style="margin-left:10px">试听中...</span>
        </el-row>
        <el-row>
          <el-button size="mini" @click="handleTrailStop">停 止</el-button>
        </el-row>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'

import { makeCall } from '@/api/data'
export default {
  props: {
    open: Boolean,
    broad: Array,
    tel: String,
    flowId: String,
    isDataManage: Boolean, //数据管理进入，不显示某些按钮
    broadcastForm: Object,
  },
  computed: {
    ...mapGetters(['operatorCallTels']),
  },
  data() {
    return {
      title: '语音文件列表',
      editTitle: '',
      searchKey: '',
      tableData: [],
      checkedRows: [],
      currentRow: undefined,
      form: {},
      editVisible: false,
      trialVisible: false,
      trailPhone: '', // 试听号码
      accept: '.mp3,.au,.wav',
      uploadHeaders: {
        FileType: 'filebroadcast',
        ContentType: 'multipart/form-data',
      },
      fileList: [],
      uploading: false,
      rules: { orifilename: [{ required: true, message: '请选择文件' }] },
      isAdmin: 0,
    }
  },
  methods: {
    // 文件上传确定按钮
    uploadVoice() {
      this.uploading = true
      this.$refs['edit-form'].validateField('orifilename', (err) => {
        if (err) {
          this.uploading = false
          return
        }
      })
      if (this.form.remark) this.uploadHeaders.remark = this.form.remark
      this.$refs['upload-file'].submit()
    },
    // 文件状态事件
    uploadChange(file, fileList) {
      console.log('uploadChange', file.status)
      if (file.status === 'ready') {
        if (fileList.length > 1) {
          this.fileList = [file]
        }
        this.$set(this.form, 'orifilename', file.name)
        this.$set(this.form, 'filesize', Math.ceil(file.size / 1024))
        this.$refs['edit-form'].clearValidate()
      } else if (file.status === 'success') {
        if (file.response.msg === 'fail') {
          console.log('上传文件失败', file.response.reason)
          this.$message({
            message: '上传文件失败',
            type: 'error',
            showClose: true,
            duration: 3 * 1000,
          })
        } else {
          setTimeout(() => {
            this.initData()
          }, 1800)
        }
        this.$refs['upload-file'].clearFiles()
        this.editVisible = false
      }
    },
    // 获取文件上传url
    uploadUrl() {
      return SDK.idispatchServer() + '/fileflow'
    },
    // 高亮行变化
    currentRowChange(currentRow, oldCurrentRow) {
      this.currentRow = currentRow
      // console.log('currentRowChange', currentRow.orifilename)
    },
    // 选择框改变是触发
    selectionChange(rows) {
      this.checkedRows = rows
    },
    // 对数据进行过滤
    filterData() {
      if (!this.searchKey) return this.tableData
      return this.tableData.filter((data) =>
        data.orifilename.toLowerCase().includes(this.searchKey.toLowerCase())
      )
    },
    // 试听按钮
    handleTrail(row) {
      if (!this.trailPhone) {
        if (!this.operatorCallTels) {
          this.$message({
            message: '没有可操作的手柄',
            type: 'error',
            showClose: true,
            duration: 3 * 1000,
          })
          return
        }
        this.trailPhone = this.operatorCallTels[0]
      }
      SDK.voiceFileListen(this.trailPhone, row.fileid, row.orifilename).then(
        (res) => {
          this.trialVisible = true
        }
      )
    },
    // 停止试听按钮
    handleTrailStop() {
      this.trialVisible = false
      SDK.voiceFileListenStop(this.trailPhone)
    },
    // 更新文件
    updateVoice() {
      console.log('updateVoice')
      SDK.voiceFileMod(
        this.form.fileid,
        this.form.filename,
        this.orifilename,
        this.form.remark
      )
        .then((res) => {
          this.editVisible = false
        })
        .catch((err) => {
          this.$message({
            message: '更新文件失败',
            type: 'error',
            showClose: true,
            duration: 3 * 1000,
          })
        })
    },
    // 编辑按钮
    handleEdit(row) {
      console.log('handleEdit', JSON.stringify(row))
      this.form = row
      this.form.filesize = Math.ceil(row.voiceSize / 1024)
      this.editTitle = '语音文件编辑'
      this.editVisible = true
    },
    // 确定按钮
    handleCommit() {
      console.log('handleCommit')
      let file =
        this.currentRow ||
        (this.checkedRows.length === 1 ? this.checkedRows[0] : null)
      if (!file) {
        this.$message({
          message: '请选择一项数据',
          type: 'error',
          showClose: true,
          duration: 3 * 1000,
        })
        return
      }
      this.flowId
      let time = null
      if (this.broadcastForm.type == 0) {
        time = null
      } else {
        time = this.broadcastForm.num
      }
      makeCall({
        request: {
          '@id': '100000',
          '@type': 'BroadcastCall',
          callingDevice: this.tel,
          called: this.flowId ? '' : this.broad,
          callMode: 'file',
          fileName: file.filename,
          time: time,
          callLoop: 0,
          flowID: this.flowId,
        },
      }).then((res) => {
        if (res.data.msg == 'try') {
          this.$emit('handleFileCall', file.filename)
        }
      })
    },
    filterTable() {
      this.filterData()
    },
    // 上传按钮
    handleUpload() {
      this.form = {}
      this.editTitle = '语音文件上传'
      this.uploading = false
      this.editVisible = true
    },
    // 删除按钮
    handleDelete() {
      if (this.checkedRows.length === 0) {
        this.$message({
          message: '请至少选择一项',
          type: 'error',
          showClose: true,
          duration: 3 * 1000,
        })
        return
      }
      const self = this
      this.$confirm('确定要删除选中项吗？', '提示', {
        distinguishCancelAndClose: true,
        showClose: false,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(async () => {
          for (let i = 0; i < self.checkedRows.length; i++) {
            SDK.deleteFile(self.checkedRows[i].fileid)
              .then((res) => {
                // if (res == 'msg: "success"') {
                //   debugger
                // }
                self.initData()
              })
              .catch((err) => {})
          }
          // setTimeout(() => {
          //   self.initData()
          // }, 1800)
        })
        .catch((err) => {})
    },
    // 关闭弹出窗
    handleClose() {
      this.$emit('update:open', false)
    },
    // 获取表格数据
    initData() {
      this.isAdmin = sessionStorage.getItem('isAdmin')
      SDK.voiceFileList().then((res) => {
        this.tableData = res.VoiceFileList
      })
    },
  },
  mounted() {
    this.initData()
  },
}
</script>

<style lang="scss" scoped>
/deep/.broadcast-dialog {
  cursor: default;
  background-color: #1a4969;
  .el-dialog__header {
    padding-top: 10px;
    text-align: center;
    .el-dialog__title {
      color: #fff;
    }
    .el-dialog__close {
      color: #fff;
    }
  }
  .el-dialog__body {
    padding: 0 15px;
    .search-input {
      margin-bottom: 10px;
      .el-input__inner {
        background-color: #1a4969;
        color: #fff;
      }
    }
  }
  .el-dialog__footer {
    padding-bottom: 10px;
    .el-button {
      background-color: #1a4969;
      color: #fff;
      width: 70px;
    }
    .el-button:hover {
      background-color: #00b2ee;
    }
  }
  .el-table {
    td {
      border-bottom: 1px solid #2e67a8;
    }
    tr:hover > td {
      background-color: #2f6b8d;
    }
    background-color: #1a4969;
    .table-herder-custom {
      background-color: #2e67a8;
      color: #fff;
    }
    .table-cell-custom {
      background-color: #172a47;
      color: #fff;
      .el-link {
        color: #fff;
        margin-left: 20px;
        span {
          font-size: 10px;
        }
        &:hover {
          color: #06f7bb;
        }
      }
    }
    /deep/.el-table__body tr.current-row > td {
      background: #6bb5e6 !important;
    }
  }
  .el-dialog__wrapper {
    position: absolute;
    height: 100%;
    .inner-dialog {
      background-color: #1a4969;
      height: 100%;
      margin-top: 0 !important;
      margin-bottom: 0px;
      opacity: 0.96;
      .el-dialog__footer {
        position: absolute;
        bottom: 0px;
        right: 0px;
      }
      .back-to-list {
        color: #fff;
        height: 22px;
        width: 22px;
      }
      .el-form {
        .el-form-item__label {
          color: #fff;
        }
        .el-input__inner,
        .el-textarea__inner {
          background-color: #1a4969;
          color: #fff;
        }
      }
      .el-upload {
        .el-button {
          color: #fff;
          background-color: #1a4969;
          margin-top: 10px;
          &:hover {
            background-color: #00b2ee;
          }
        }
      }
    }

    .trial-box {
      position: absolute;
      left: calc(50% - 100px);
      top: calc(50% - 50px);
      border: 1px solid rgba(255, 255, 255, 0.6);
      border-radius: 5px;
      width: 200px;
      height: 100px;
      display: flex;
      flex-flow: column;
      align-items: center;
      justify-content: center;
      .el-row {
        color: #fff;
      }
      .trial-loading {
        width: 20px;
        height: 20px;
        border-radius: 50%;
        -webkit-animation: loading 1.1s infinite linear;
        animation: loading 1.2s infinite linear;
        @-webkit-keyframes loading {
          from {
            transform: rotate(0deg);
          }
          to {
            transform: rotate(360deg);
          }
        }
        @keyframes loading {
          from {
            transform: rotate(0deg);
          }
          to {
            transform: rotate(360deg);
          }
        }
      }
      .el-button {
        width: 70px;
        color: #fff;
        background-color: #1a4969;
        margin-top: 10px;
        &:hover {
          background-color: #00b2ee;
        }
      }
    }
  }
}
</style>
